import { _decorator, Component, Node, Label, ProgressBar, debug } from 'cc';
import { TaskManager } from "../Controller/TaskManager";
import TaskRecord from "../Controller/TaskRecord";
import TaskVO from "../Model/TaskVO";
import { UIBase } from '../../../[框架]/通用UI/UIBase';

const { ccclass, property } = _decorator;

@ccclass('TaskCell')
export default class TaskCell extends UIBase {

    @property(Label)
    private txtName: Label = null;

    @property(Label)
    private txtFinishTime: Label = null;

    @property(Node)
    private btnAD: Node = null;

    @property(Node)
    private btnDone: Node = null;

    @property(Node)
    private layoutAwards: Node = null;

    @property(ProgressBar)
    private progress: ProgressBar = null;

    private cdLabel: Label = null;

    private taskVO: TaskVO;


    onLoad() {
        this.btnAD.off(Node.EventType.TOUCH_END, this.onAD, this);
        this.cdLabel = this.btnAD.getComponentInChildren(Label);
    }

    onEnable() {
        this.btnAD.on(Node.EventType.TOUCH_END, this.onAD, this);
    }

    public reset() {
        this.txtFinishTime.string = "";
        this.txtName.string = "任务";
        this.taskVO = null;
        this.progress.progress = 0;
        let txtPro = this.progress.getComponentInChildren(Label);
        if (txtPro) {
            txtPro.string = "0/0";
        }
        this.btnAD.active = false;
        this.btnDone.active = false;
        this.cdLabel.string = "去完成";
    }

    public updateUI(model: TaskVO) {
        this.reset();
        this.taskVO = model;
        this.txtName.string = model.ad_task_name;
        let curCount = model.m_finishCount;
        this.progress.progress = curCount / model.ad_task_count;
        let txtPro = this.progress.getComponentInChildren(Label);
        if (txtPro) {
            txtPro.string = `${curCount}/${model.ad_task_count}`;
        }
        this.btnAD.active = model.m_status == "进行中";
        this.btnDone.active = model.m_status == "已完成";
        this.layoutAwards.active = model.m_status != "已完成";
        if (model.m_status == "已完成") {
            let rec = TaskRecord.getTaskStatus(model.m_task_id);
            let time = Guyu.DayLite.create(rec.finish_time).format("YYYY-MM-DD HH:mm:ss");
            this.txtFinishTime.string = `完成时间:${time}`;
        }
    }

    private onAD() {
        if (this.taskVO) {
            TaskManager.doTask(this.taskVO);
        }
    }

    update(deltaTime: number): void {
        this.calcTaskCD();
    }

    private calcTaskCD() {
        if (!this.taskVO) {
            return;
        }
        let cd = TaskManager.caleCDTime(this.taskVO);
        if (cd <= 0) {
            this.cdLabel.string = "去完成";
        } else {
            this.cdLabel.string = Guyu.Tools.secondsToCountdown(cd);
        }
    }
}
